<!-- 商品发布 - 库存价格 -->
<template>
  <el-form ref="formRef" :disabled="isDetail" :model="formData" :rules="rules" label-width="120px">
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center justify-between bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>{{ propertyList[0]?.name }}</span>
      <el-button class="mr-15px" @click="attributesAddFormOpen">添加规则</el-button>
    </div>
    <el-tabs v-model="editableTabsValue" type="card" closable @edit="handleTabsEdit">
      <template v-if="formData.specType && propertyList.length > 0">
        <SkuList
          ref="skuListRef"
          :is-detail="isDetail"
          :prop-form-data="formData"
          :property-list="propertyList"
          :rule-config="ruleConfig"
          :prop-form-rules="rules"
        />
      </template>
    </el-tabs>
  </el-form>
  <!-- 商品属性添加 Form 表单 -->
  <ProductPropertyAddForm
    ref="attributesAddFormRef"
    :propertyList="propertyList"
    @success="generateSkus"
  />
</template>
<script lang="ts" setup>
import { PropType } from 'vue'
import { copyValueToTarget, generateSortNumericUUID } from '@/utils'
import { propTypes } from '@/utils/propTypes'
import {
  getPropertyList,
  PropertyAndValues,
  RuleConfig
} from '@/views/mall/product/spu/components/index'
import SkuList from './../components/SkuList.vue'
import ProductPropertyAddForm from './../components/ProductPropertyAddForm.vue'
import type { Spu } from '@/api/mall/product/spu'
defineOptions({ name: 'ProductSpuPaidSkuForm' })

// sku 相关属性校验规则
const ruleConfig: RuleConfig[] = []

const message = useMessage() // 消息弹窗

const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },
  isDetail: propTypes.bool.def(false), // 是否作为详情组件
  activeName: propTypes.string.def('sku')
})
const attributesAddFormRef = ref() // 添加商品属性表单
const formRef = ref() // 表单 Ref
const propertyList = ref<PropertyAndValues[]>([]) // 商品属性列表
const skuListRef = ref() // 商品属性列表 Ref
const formData = reactive<Spu>({
  specType: true, // 商品规格
  spuType: 5, //商品类型
  spuId: undefined,
  skus: []
})

const rules = reactive({
  picUrl: [{ required: true, message: '请选择图片', trigger: 'blur' }],
  specType: [required],
  expiryDate: [required],
  price: [{ required: true, message: '请输入零售价', trigger: 'blur' }]
})
const attributesAddFormOpen = () => {
  attributesAddFormRef.value.open()
}
/**付费会员 */
import type { TabPaneName } from 'element-plus'

const editableTabsValue = ref('1')
const editableTabs = ref([] as EmptyArrayType)
const handleTabsEdit = (targetName: TabPaneName | undefined, action: 'remove' | 'add') => {
  if (action === 'add') {
    const newTabName = `${targetName}`
    editableTabs.value.push({
      title: `${newTabName}`,
      name: newTabName,
      content: ''
    })
    editableTabsValue.value = newTabName
  } else if (action === 'remove') {
    console.log('remove')
    const tabs = editableTabs.value
    let activeName = editableTabsValue.value

    if (activeName === targetName) {
      tabs.forEach((tab, index) => {
        if (tab.name === targetName) {
          propertyList.value[0].values?.splice(index, 1)

          const nextTab = tabs[index + 1] || tabs[index - 1]
          if (nextTab) {
            activeName = nextTab.name
          }
        }
      })
    }
    console.log(activeName)

    editableTabsValue.value = activeName
    editableTabs.value = tabs.filter((tab) => tab.name !== targetName)
    formData.skus?.forEach((ele, index) => {
      if (ele.tabsName == targetName) {
        formData.skus?.splice(index, 1)
      }
    })
  }
}

/** 初始化付费会员的规格项 付费周期 */
// import * as PropertyApi from '@/api/mall/product/property'

const initPropertyList = async () => {
  let formData = {
    name: '付费周期'
  }
  // const data = formData as PropertyApi.PropertyVO
  // const propertyId = await PropertyApi.createProperty(data)
  const propertyId = generateSortNumericUUID()

  // 添加到属性列表
  propertyList.value.push({
    id: propertyId,
    ...formData,
    values: []
  })
  attributesAddFormRef.value.initAttribute()
}

onMounted(() => {})
/** 将传进来的值赋值给 formData */
watch(
  () => props.propFormData,
  (data) => {
    if (!data) {
      return
    }
    copyValueToTarget(formData, data)
    // 将 SKU 的属性，整理成 PropertyAndValues 数组
    propertyList.value = getPropertyList(data)
  },
  {
    // deep: true,
    immediate: true
  }
)

/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
  if (!formRef) return
  try {
    // 校验 sku
    await skuListRef.value?.validateSku()

    // await unref(formRef).validate()

    // 校验通过更新数据
    Object.assign(props.propFormData, formData)
  } catch (e) {
    message.error('【规则】不完善，请填写相关信息')
    emit('update:activeName', 'info')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate, initPropertyList, handleTabsEdit })

/** 调用 SkuList generateTableData 方法*/
const generateSkus = (propertyList: any[]) => {
  console.log(propertyList)
  skuListRef.value.generateTableData(propertyList)
  Object.assign(props.propFormData, formData)
  handleTabsEdit(propertyList[0].values[propertyList[0].values.length - 1].name, 'add')
}
</script>
